import { RootState } from '@/types/store'
import { useAppDispatch, useAppSelector } from "@/store/hooks"
import type { Action, ThunkAction } from '@reduxjs/toolkit'
import { useEffect } from "react"

function useApiData<Key extends keyof RootState>
  (
    thunkFn: () => ThunkAction<void, RootState, unknown, Action>,
    key: Key
  ) {
  const dispatch = useAppDispatch()
  const state = useAppSelector((state) => state[key])
  useEffect(() => {
    dispatch(thunkFn())
  }, [dispatch, thunkFn])
  return state
}

export default useApiData
